import {messages, queryCurrencyPrecision} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import config from 'config'
import menuRoute from 'routes/menuRoute'
import { Radio, Badge, Table, Pagination, message, Alert, Icon, Dropdown, Menu, Modal, Form,
  DatePicker, Spin } from 'antd'
const FormItem = Form.Item;
import paymentService  from 'containers/pay/pay-workbench/pay-workbench.service'
import Condition from 'components/condition'
import CheckModal from 'containers/pay/template/check-modal'
const { If } = Condition;
import moment from 'moment';
import ImportModal from "components/template/import-modal-ie/import-modal";
import CostCenterSearchForm from 'components/template/cost-center-search-form/cost-center-search-form'
import SearchArea from 'components/search-area'
import baseService from 'share/base.service'

class PayPaying extends React.Component {
  constructor(props) {
    super(props);
    const userJobsDTOs = [];
    props.user.companyWithUserJobsDTOList.map(item => {
      item.userJobsDTOList.map(it => {
        userJobsDTOs.push(it);
      })
    });
    this.mainJob = userJobsDTOs.filter(item => item.companyMainPosition)[0];
    this.state = {
      radioValue: '',
      partnerId: undefined,
      searchForm: [
        {
          type: 'list', isRequired: true,listType: 'permission_company',
          id: 'paymentCompanyId',
          defaultValue: props.tenantMode ? [{name: this.mainJob.companyName, id: this.mainJob.companyId}] : [{name: props.company.name, id: props.company.id}],
          label: messages('pay.key137')/*单据公司*/,
          labelKey: 'name',
          valueKey: 'id',
          single: true,
          listExtraParams:{enabled: true}
        },//付款机构选择
        {type: 'input', id: 'documentNumber', label: messages('pay.key13'/*单据编号*/)}, //单据编号
        {type: 'value_list', id: 'documentCategory', label: messages('pay.key14'/*单据类型*/), options: [], valueListCode: 2106}, //单据类型
        {
          type: 'list', listType: "select_authorization_user", options: [], id: 'employeeId', label: messages('pay.key15'/*申请人*/), labelKey: "userCode",
          valueKey: "userId", single: true
        }, //申请人
        {type: 'items', id: 'amountRange', items: [
          {type: 'input', id: 'amountFrom', label: messages('pay.key16'/*支付金额从*/)},
          {type: 'input', id: 'amountTo', label: messages('pay.key17'/*支付金额至*/)}
        ]},
        {
          type: 'items', id: 'partner', items: [
            {
              type: 'value_list',
              id: 'partnerCategory',
              label: messages('pay.key18')/*类型*/,
              valueListCode: 2107,
              options: [],
              event: 'code'
            },
            {
              type: 'list',
              id: 'partnerId',
              label: messages('pay.key19')/*收款方*/,
              listType: 'user',
              single: true,
              disabled: true,
              labelKey: 'fullName',
              valueKey: "id"
            },
          ]
        },
        {type: 'input', id: 'billcode', label: messages('pay.key20'/*付款流水号*/)},
        {type: 'input', id: 'customerBatchNo', label: messages('pay.key21'/*付款批次号*/)},
        {type: 'items', id: 'dateRange', items: [
          {type: 'date', id: 'payDateFrom', label: messages('pay.key56'/*支付日期从*/)},
          {type: 'date', id: 'payDateTo', label: messages('pay.key57'/*支付日期至*/)}
        ]},
        {
          type: 'list', id: 'departmentOids', label: messages('financial-management.key195'/*部门*/),
          listType: 'department', labelKey: 'name', valueKey: 'departmentOid'
        }
      ],
      searchParams: { paymentCompanyId: props.tenantMode ? this.mainJob.companyId : props.company.id },
      columns: [
        {title: messages('pay.key20'/*付款流水号*/), dataIndex: 'billcode', render: (value, record) => <a onClick={() => {this.checkPaymentDetail(record)}}>{value}</a>},
        {title: messages('pay.key22'/*单据编号 | 单据类型*/), dataIndex: 'documentNumber', render: (value, record) => {
          return (
            <div>
              <a onClick={() => {this.checkPaymentDetail(record)}}>{value}</a>
              <span className="ant-divider"/>
              {record.documentTypeName}
            </div>
          )}
        },
        {title: messages('pay.key21'/*付款批次号*/), dataIndex: 'customerBatchNo'},
        {title: messages('pay.key23'/*工号 | 申请人*/), dataIndex: 'employeeName', render: (value, record) => {
          return (
            <div>
              {record.employeeId}
              <span className="ant-divider"/>
              {value}
            </div>
          )}
        },
        {title: messages('common.currency')/*币种*/, dataIndex: 'currency'},
        {title: messages('pay.key24'/*本次支付金额*/), dataIndex: 'amount', render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currency))},
        {title: messages('pay.key25'/*付款方式*/), dataIndex: 'paymentTypeName'},
        {title: messages('pay.key26'/*类型 | 收款方*/), dataIndex: 'partnerCategoryName', render: (value, record) => {
          return (
            <div>
              {value}
              <span className="ant-divider"/>
              {record.partnerName}
            </div>
          )}
        },
        {title: messages('pay.key27'/*收款方账号*/), dataIndex: 'payeeAccountNumber'},
        {title: messages('pay.key58'/*支付日期*/), dataIndex: 'payDate', render: value => moment(value).format('YYYY-MM-DD')},
        {title: messages('common.column.status')/*状态*/, dataIndex: 'paymentStatusName', render: (state) => <Badge status='processing' text={state}/>},
        {title: messages('common.operation')/*操作*/, dataIndex: 'id', fixed: 'right', render: (id, record) => {
          const menu = (
            <Menu>
              <Menu.Item>
                <a onClick={() => this.handleSuccess(record)}>{messages('pay.key59'/*确认成功*/)}</a>
              </Menu.Item>
              <Menu.Item>
                <a onClick={() => this.handleFail(record)}>{messages('pay.key60'/*确认失败*/)}</a>
              </Menu.Item>
            </Menu>
          );
          return (
            <div>
              <a onClick={() => {this.checkPaymentDetail(record)}}>{messages('common.view')/*查看*/}</a>
              {record.paymentStatus !== 'W' && (
                <span>
                  <span className="ant-divider"/>
                  <Dropdown overlay={menu} placement="bottomRight"><a>{messages('common.more')/*更多*/}<Icon type="down" /></a></Dropdown>
                </span>
              )}
            </div>
          )}
        }
      ],
      okModalVisible: false, //确认成功modal
      failModalVisible: false, //确认失败modal
      record: {}, //点击行信息
      confirmSuccessLoading: false,
      confirmFailLoading: false,
      pageSizeOptions: ['10', '20', '30', '50'],

      /* 线上 */
      onlineLoading: false,
      onlineData: [],
      onlinePage: 0,
      onlinePageSize: 10,
      onlinePagination: {
        total: 0
      },
      onlineCash: [],  //总金额
      onlineWarningRows: [],  //超过12小时未更新状态行

      /* 落地文件 */
      fileLoading: false,
      fileData: [],
      filePage: 0,
      filePageSize: 10,
      filePagination: {
        total: 0
      },
      fileCash: [],  //总金额
      fileWarningRows: [],  //超过12小时未更新状态行
      failData: moment(new Date()),
      isDetail: false,
      paymentDetail:  menuRoute.getRouteItem('payment-detail','key'),    //支付详情

      searchCostCenterCommands: null,
      radioOption: [],
      loading: false
    };
  }

  componentWillMount() {
    this.getList();
    this.getFinanceConfig();
  }

  getFinanceConfig = () => {
    let companyId = this.state.searchParams.paymentCompanyId;
    this.setState({ loading: true });
    Promise.all([
      baseService.getFinanceConfig({ companyId, itemGroupCode: 'PAYMENT_1_G1' }),
      baseService.getFinanceConfig({ companyId, itemGroupCode: 'PAYMENT_1_G2' })
    ]).then(res => {
      this.setState({
        loading: false,
        radioOption: this.props.orderTab(res[0].data),
        radioValue: res[1].data[0].itemCode
      });
    }).catch(() => {
      this.setState({ loading: false });
      message.error(messages('pay.key225')/*系统异常*/);
    });
  };

  getList = () => {
    let online = new Promise((resolve, reject) => {
      this.getOnlineList(resolve, reject)
    });
    let file = new Promise((resolve, reject) => {
      this.getFileList(resolve, reject)
    });
    Promise.all([ online, file ]).then(() => {
      this.getOnlineCash();
      this.getFileCash();
    }).catch(() => {
      message.error(messages('pay.key29'/*数据加载失败，请重试*/))
    })
  };

  search = (values) => {
    const { searchCostCenterCommands } = this.state;
    values.payDateFrom && (values.payDateFrom = moment(values.payDateFrom).format('YYYY-MM-DD'));
    values.payDateTo && (values.payDateTo = moment(values.payDateTo).format('YYYY-MM-DD'));
    if(!!this.state.partnerId){
      values.partnerId=this.state.partnerId;
    }else {
      values.partnerId && values.partnerId.length>0 && (values.partnerId = values.partnerId[0].id)
    }
    if(searchCostCenterCommands){
      paymentService.getCostCenterId(searchCostCenterCommands).then(res => {
        values.costCenterItemOids = res.data;
        this.setState({
          searchParams: values,
          onlineCash: [],
          fileCash: []
        }, () => {
          this.getList()
        })
      }).catch(e => {
        message.error(e.response.data.message);
      })
    } else {
      this.setState({
        searchParams: values,
        onlineCash: [],
        fileCash: []
      }, () => {
        this.getList();
        this.getFinanceConfig();
      })
    }
  };

  clear = () => {
    this.setState({searchCostCenterCommands: null},() => {
      this.eventHandle('code', null, '1');
    });
  };

  eventHandle = (type, value, search) => {
    let { searchForm, partnerId } = this.state;
    if (type === 'code') {
      partnerId = undefined;
      value = value ? value : "";
      this.formRef.setValues({partnerId: undefined});
      if (value === "EMPLOYEE") {
        let item = searchForm[5];
        item.items[1].disabled = false;
        item.items[1].listType = 'user';
        item.items[1].labelKey = 'fullName';
        searchForm[5] = item;
      }
      if (value === "VENDER") {
        let item = searchForm[5];
        item.items[1].disabled = false;
        item.items[1].listType = 'finance_vendor';
        item.items[1].labelKey = 'venNickname';
        searchForm[5] = item;
      }
      if (value === "") {
        let item = searchForm[5];
        item.items[1].disabled = true;
        searchForm[5] = item;
      }
      this.setState({ searchForm: searchForm, partnerId },() => {
        search === '1' && this.formRef.handleSearch();
      })
    }
  };

  //查看支付流水详情
  checkPaymentDetail = (record) => {
    this.context.router.push(this.state.paymentDetail.url.replace(':tab', 'Paying').replace(':id', record.id));
  };

  //确认成功弹框
  handleSuccess = (record) => {
    this.props.form.setFieldsValue({ date: undefined });
    this.setState({ record, okModalVisible: true })
  };

  //确认成功操作
  confirmSuccess = () => {
    let date = this.props.form.getFieldValue('date');
    if(date){
      date = moment(date).format('YYYY-MM-DD');
      let params = {
        detailIds: [this.state.record.id],
        versionNumbers: [this.state.record.versionNumber]
      };
      this.setState({ confirmSuccessLoading: true });
      date = new Date(date).format('yyyy-MM-dd') === new Date().format('yyyy-MM-dd') ? new Date().format('yyyy-MM-dd hh:mm:ss') : new Date(date).format('yyyy-MM-dd 23:59:59')
      paymentService.confirmSuccess(params, date).then(res => {
        if (res.status === 200) {
          message.success(messages('common.operate.success')/*操作成功*/);
          this.setState({ confirmSuccessLoading: false, okModalVisible: false });
          this.getList()
        }
      }).catch(() => {
        this.setState({ confirmSuccessLoading: false });
        message.error(e.response.data.message);
      })
    }
  };

  //确认失败弹框
  handleFail = (record) => {
    this.setState({ record, failModalVisible: true })
  };

  //确认失败操作
  confirmFail = () => {
    let params = {
      detailIds: [this.state.record.id],
      versionNumbers: [this.state.record.versionNumber]
    };
    this.setState({ confirmFailLoading: true });
    paymentService.confirmFail(params).then(res => {
      if (res.status === 200) {
        message.success(messages('common.operate.success')/*操作成功*/);
        this.setState({ failModalVisible: false, confirmFailLoading: false });
        this.getList()
      }
    }).catch(e => {
      this.setState({ confirmFailLoading: false });
      message.error(e.response.data.message)
    })
  };

  /*********************** 获取总金额 ***********************/

  //线上
  getOnlineCash = () => {
    paymentService.getAmount('ONLINE_PAYMENT', 'P', this.state.searchParams).then(res => {
      this.setState({ onlineCash: res.data })
    })
  };

  //落地文件
  getFileCash = () => {
    paymentService.getAmount('EBANK_PAYMENT', 'P', this.state.searchParams).then(res => {
      this.setState({ fileCash: res.data })
    })
  };

  /************************ 获取列表 ************************/

  //线上
  getOnlineList = (resolve, reject) => {
    const { onlinePage, onlinePageSize, searchParams } = this.state;
    this.setState({ onlineLoading: true });
    paymentService.getPayingList(onlinePage, onlinePageSize, 'ONLINE_PAYMENT', searchParams).then(res => {
      if (res.status === 200) {
        let onlineWarningRows = [];
        res.data.map(item => {
          if ((new Date().getTime() - new Date(item.payDate).getTime())/1000/60/60 > 12) {  //付款时间超过12小时
            onlineWarningRows.push(item)
          }
        });
        this.setState({
          onlineData: res.data,
          onlineLoading: false,
          onlineWarningRows,
          onlinePagination: {
            total: Number(res.headers['x-total-count']) ? Number(res.headers['x-total-count']) : 0
          }
        });
        reject && resolve()
      }
    }).catch(() => {
      this.setState({ onlineLoading: false });
      reject && reject()
    })
  };

  //落地文件
  getFileList = (resolve, reject) => {
    const { filePage, filePageSize, searchParams } = this.state;
    this.setState({ fileLoading: true });
    paymentService.getPayingList(filePage, filePageSize, 'EBANK_PAYMENT', searchParams).then(res => {
      if (res.status === 200) {
        let fileWarningRows = [];
        res.data.map(item => {
          if ((new Date().getTime() - new Date(item.payDate).getTime())/1000/60/60 > 12) {  //付款时间超过12小时
            fileWarningRows.push(item)
          }
        });
        this.setState({
          fileData: res.data,
          fileLoading: false,
          fileWarningRows,
          filePagination: {
            total: Number(res.headers['x-total-count']) ? Number(res.headers['x-total-count']) : 0
          }
        });
        resolve && resolve()
      }
    }).catch(() => {
      this.setState({ fileLoading: false });
      reject && reject()
    })
  };

  /********************* 修改每页显示数量 *********************/

  //线上
  onlinePaginationChange = (onlinePage, onlinePageSize) => {
    onlinePage = onlinePage - 1;
    this.setState({ onlinePage, onlinePageSize },() => {
      this.getOnlineList()
    })
  };

  //落地文件
  filePaginationChange = (filePage, filePageSize) => {
    filePage = filePage - 1;
    this.setState({ filePage, filePageSize },() => {
      this.getFileList()
    })
  };

  /************************ 内容渲染 ************************/

  //线上
  renderOnlineContent = () => {
    const { columns, onlineData, onlineLoading, onlinePageSize, onlinePagination, onlineCash, onlineWarningRows, pageSizeOptions } = this.state;
    const tableTitle = (
      <div> {messages('pay.key62'/*支付中*/)}
        {onlineCash.length > 0 && <span className="ant-divider"/>}
        {onlineCash.map((item, index) => {
          return (
            <div key={index} style={{display:'inline-block'}}> {messages('pay.key132',{arg1:item.currency}/*金额：{arg1}*/)} <span className="num-style">{this.filterMoney(item.totalAmount, queryCurrencyPrecision(item.currency), true)}</span>
              <span className="ant-divider"/> {messages('pay.key37'/*交易笔数：*/)}<span className="num-style">{item.documentNumber}{messages('pay.key38'/*笔*/)}</span>
              {index !== onlineCash.length - 1 && <span className="ant-divider"/>}
            </div>
          )
        })}
      </div>
    );
    return (
      <div className="paying-online">
        <Table rowKey={record => record.id}
               columns={columns}
               dataSource={onlineData}
               pagination={false}
               loading={onlineLoading}
               title={()=>{return tableTitle}}
               scroll={{x: true, y: false}}
               rowClassName={record => {
                 let warningFlag = false;
                 onlineWarningRows.map(item => {
                   item.id === record.id && (warningFlag = true)
                 });
                 return warningFlag ? 'row-warning' : ''
               }}
               bordered
               size="middle"/>
        <Pagination size="small"
                    defaultPageSize={onlinePageSize}
                    showSizeChanger
                    pageSizeOptions={pageSizeOptions}
                    total={onlinePagination.total}
                    onChange={this.onlinePaginationChange}
                    onShowSizeChange={this.onlinePaginationChange}
                    style={{margin:'16px 0', textAlign:'right'}} />
      </div>
    )
  };

  //落地文件
  renderFileContent = () => {
    const { columns, fileData, fileLoading, filePageSize, filePagination, fileCash, fileWarningRows, pageSizeOptions } = this.state;
    const tableTitle = (
      <div> {messages('pay.key62'/*支付中*/)}
        {fileCash.length > 0 && <span className="ant-divider"/>}
        {fileCash.map((item, index) => {
          return (
            <div key={index} style={{display:'inline-block'}}> {messages('pay.key132',{arg1:item.currency}/*金额：{arg1}*/)} <span className="num-style">{this.filterMoney(item.totalAmount, queryCurrencyPrecision(item.currency), true)}</span>
              <span className="ant-divider"/> {messages('pay.key37'/*交易笔数：*/)}<span className="num-style">{item.documentNumber}{messages('pay.key38'/*笔*/)}</span>
              {index !== fileCash.length - 1 && <span className="ant-divider"/>}
            </div>
          )
        })}
      </div>
    );
    return (
      <div className="paying-file">
        <Table rowKey={record => record.id}
               columns={columns}
               dataSource={fileData}
               pagination={false}
               loading={fileLoading}
               title={()=>{return tableTitle}}
               scroll={{x: true, y: false}}
               rowClassName={record => {
                 let warningFlag = false;
                 fileWarningRows.map(item => {
                   item.id === record.id && (warningFlag = true)
                 });
                 return warningFlag ? 'row-warning' : ''
               }}
               bordered
               size="middle"/>
        <Pagination size="small"
                    defaultPageSize={filePageSize}
                    showSizeChanger
                    pageSizeOptions={pageSizeOptions}
                    total={filePagination.total}
                    onChange={this.filePaginationChange}
                    onShowSizeChange={this.filePaginationChange}
                    style={{margin:'16px 0', textAlign:'right'}} />
      </div>
    )
  };
  //日期限制
  disabledDate = (current) => {
    return current && current.valueOf() > Date.now();
  };

  handleChooseData = value => {
    this.setState({failData: value})
  };

  changeCostCenter = (value) => {
    this.setState({searchCostCenterCommands: value})
  };

  handleFileOrDetail = e => {
    this.setState({isDetail: e.target.value === '2'});
  };

  /************************* End *************************/

  render(){
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 15, offset: 1 },
    };
    const { radioValue, searchForm, okModalVisible, failModalVisible, onlineWarningRows, fileWarningRows, confirmSuccessLoading,
      confirmFailLoading, failData, searchCostCenterCommands, isDetail, loading, radioOption } = this.state;
    let warningItems = radioValue === 'ONLINE_PAYMENT' ? onlineWarningRows : fileWarningRows;
    let rightContent = <div>
      <Alert
        message={<div><span style={{marginRight:10,fontSize:14}}>{messages('pay.key65'/*将付款状态更改为*/)}</span><Badge status="success" text={messages('pay.key66'/*支付成功*/)}/></div>}
        description={<div style={{fontSize:12,color:'red'}}>{messages('pay.key67'/*请通过网银或询问银行的方式确认该笔付款已成功转账*/)}</div>}
        type="warning"
        showIcon
      />
      <div>
        <div style={{height: "40px", backgroundColor: "#f8f8f8", color: "#666", lineHeight: "40px", fontSize: "14px", margin: "15px -24px 0px", fontWeight: 500}}>
          <span style={{marginLeft: '24px'}}>{messages('pay.key216')/*选择导入模版*/}</span>
        </div>
        <Form>
          <FormItem style={{margin:'20px 0 10px'}}>
            {getFieldDecorator('isDetail', {
              rules: [{
                required: true,
                message: messages('common.select')/*请选择*/
              }],
              initialValue: '1'
            })(
              <Radio.Group onChange={this.handleFileOrDetail}>
                <Radio value={'1'}>{messages('pay.key217')/*报盘文件*/}</Radio>
                <Radio value={'2'}>{messages('pay.key218')/*报盘明细*/}</Radio>
              </Radio.Group>
            )}
          </FormItem>
          <FormItem {...formItemLayout}
                    label={messages('pay.key68'/*实际付款日期*/)}
                    style={{margin:'20px 0 10px'}}>
            {getFieldDecorator('failData', {
              rules: [{
                required: true,
                message: messages('common.select')/*请选择*/
              }],
              initialValue: moment(new Date())
            })(
              <DatePicker format="YYYY-MM-DD"
                          placeholder={messages('common.select')/*请选择*/}
                          disabledDate={this.disabledDate}
                          onChange={this.handleChooseData}
                          allowClear={false}/>
            )}
          </FormItem>
        </Form>
      </div>
      <div>
        <div style={{height: "40px", backgroundColor: "#f8f8f8", color: "#666", lineHeight: "40px", fontSize: "14px", margin: "0 -24px", fontWeight: 500}}>
          <span style={{marginLeft: '24px'}}>{messages('components.key662',{arg1:messages('components.key505'/*Excel电子表格*/)}/*上传{arg1}*/)}</span>
        </div>
        <div style={{margin: '5px 0px'}}>1.{messages('financial-management.key94')/*点击【选择文件】按钮*/}</div>
        <div style={{margin: '5px 0px'}}>2.{messages('components.key663',{arg1:messages('components.key505'/*Excel电子表格*/)}/*选择你刚更新过的{arg1}，并点击确定*/)}</div>
      </div>
    </div>;
    let failContent = <div>
      <Alert
        message={<div><span style={{marginRight:10,fontSize:14}}>{messages('pay.key65'/*将付款状态更改为*/)}</span><Badge status="error" text={messages('pay.key69'/*支付失败*/)}/></div>}
        description={<div style={{fontSize:12,color:'red'}}>{messages('pay.key70'/*请务必向银行确认该付款支付失败，以免产生重复支付*/)}</div>}
        type="warning"
        showIcon
      />
      <div>
        <div style={{height: "40px", backgroundColor: "#f8f8f8", color: "#666", lineHeight: "40px", fontSize: "14px", margin: "15px -24px 0px", fontWeight: 500}}>
          <span style={{marginLeft: '24px'}}>{messages('pay.key216')/*选择导入模版*/}</span>
        </div>
        <Form>
          <FormItem style={{margin:'20px 0 10px'}}>
            {getFieldDecorator('isDetail', {
              rules: [{
                required: true,
                message: messages('common.select')/*请选择*/
              }],
              initialValue: '1'
            })(
              <Radio.Group onChange={this.handleFileOrDetail}>
                <Radio value={'1'}>{messages('pay.key217')/*报盘文件*/}</Radio>
                <Radio value={'2'}>{messages('pay.key218')/*报盘明细*/}</Radio>
              </Radio.Group>
            )}
          </FormItem>
        </Form>
      </div>
      <div>
        <div style={{height: "40px", backgroundColor: "#f8f8f8", color: "#666", lineHeight: "40px", fontSize: "14px", margin: "0 -24px", fontWeight: 500}}>
          <span style={{marginLeft: '24px'}}>{messages('components.key662',{arg1:messages('components.key505'/*Excel电子表格*/)}/*上传{arg1}*/)}</span>
        </div>
        <div style={{margin: '5px 0px'}}>1.{messages('financial-management.key94')/*点击【选择文件】按钮*/}</div>
        <div style={{margin: '5px 0px'}}>2.{messages('components.key663',{arg1:messages('components.key505'/*Excel电子表格*/)}/*选择你刚更新过的{arg1}，并点击确定*/)}</div>
      </div>
    </div>;
    return (
      <Spin className="pay-paying" spinning={loading}>
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.search}
          clearHandle={this.clear}
          eventHandle={this.eventHandle}
          wrappedComponentRef={(inst) => this.formRef = inst}
          extraFieldsIndex={10}
          extraFields={[
            <div>
              <div style={{lineHeight: '28px'}}> {messages('pay.key110')/*成本中心*/}
              </div>
              <CostCenterSearchForm title={messages('pay.key110')/*成本中心*/}
                                    type='id'
                                    value={searchCostCenterCommands}
                                    onChange={this.changeCostCenter}/>
            </div>
          ]}
        />
        <Radio.Group value={radioValue} style={{margin:'20px 0'}}
                     onChange={(e) => {this.setState({ radioValue: e.target.value })}}>
          {
            radioOption.map(item => <Radio.Button value={item.itemCode}>{item.showName}</Radio.Button>)
          }
        </Radio.Group>
        <If value={radioValue === 'EBANK_PAYMENT'}>
          <div style={{marginBottom: '10px'}}>
            <ImportModal buttonName={messages('pay.key59')/*确认成功*/}
                         hasErrInfo={false}
                         downLinks={null}
                         leftContent={null}
                         isNormalModal
                         rightContent={rightContent}
                         onCancel={() => {
                           this.setState({failData: moment(new Date()), isDetail: false});
                           this.props.form.setFieldsValue({failData: moment(new Date()), isDetail: '1'});
                           this.getList();
                         }}
                         uploadUrl={`${config.baseUrl}/payment/api/cash/transaction/details/paid/success/by/document?payDate=${new Date(failData).format('yyyy-MM-dd') === new Date().format('yyyy-MM-dd') ? new Date().format('yyyy-MM-dd hh:mm:ss') : new Date(failData).format('yyyy-MM-dd 23:59:59')}&isDetail=${isDetail}`}
                         title={messages('pay.key138')/*落地文件导入*/}/>
            <span style={{padding: '0px 5px'}}/>
            <ImportModal buttonName={messages('pay.key60')/*确认失败*/}
                         hasErrInfo={false}
                         downLinks={null}
                         leftContent={null}
                         isNormalModal
                         rightContent={failContent}
                         onCancel={() => {
                           this.setState({failData: moment(new Date()), isDetail: false});
                           this.props.form.setFieldsValue({isDetail: '1'});
                           this.getList();
                         }}
                         uploadUrl={`${config.baseUrl}/payment/api/cash/transaction/details/paid/fail/by/document?isDetail=${isDetail}`}
                         title={messages('pay.key138')/*落地文件导入*/}/>
          </div>
        </If>
        <Alert message={messages('pay.key63'/*支付结果与银行业务处理速度有关，请耐心等待*/)} type="info" showIcon style={{marginBottom:20}} />
        {warningItems.length > 0 && <Alert message={messages('pay.key219')/*请注意，存在红色底色的付款已超过12小时未更新状态！*/}
                                          type="warning"
                                          style={{margin:'-10px 0 20px'}}
                                          showIcon />}
        {radioValue === 'ONLINE_PAYMENT' && this.renderOnlineContent()}
        {radioValue === 'EBANK_PAYMENT' && this.renderFileContent()}
        <Modal visible={okModalVisible}
               confirmLoading={confirmSuccessLoading}
               onOk={this.confirmSuccess}
               onCancel={() => this.setState({ okModalVisible: false })}
               okText={messages('pay.key59'/*确认成功*/)}
               width={500}>
          <div style={{marginTop:'20px'}}>
            <Alert
              message={<div><span style={{marginRight:10,fontSize:14}}>{messages('pay.key65'/*将付款状态更改为*/)}</span><Badge status="success" text={messages('pay.key66'/*支付成功*/)}/></div>}
              description={<div style={{fontSize:12,color:'red'}}>{messages('pay.key67'/*请通过网银或询问银行的方式确认该笔付款已成功转账*/)}</div>}
              type="warning"
              showIcon
            />
            <Form style={{marginLeft:29}}>
              <FormItem {...formItemLayout}
                        label={messages('pay.key68'/*实际付款日期*/)}
                        style={{margin:'20px 0 10px'}}>
                {getFieldDecorator('date', {
                  rules: [{
                    required: true,
                    message: messages('common.select')/*请选择*/
                  }]
                })(
                  <DatePicker format="YYYY-MM-DD"
                              placeholder={messages('common.select')/*请选择*/}
                              disabledDate={this.disabledDate}
                              allowClear={false}/>
                )}
              </FormItem>
            </Form>
          </div>
        </Modal>
        <Modal visible={failModalVisible}
               confirmLoading={confirmFailLoading}
               onOk={this.confirmFail}
               onCancel={() => this.setState({ failModalVisible: false })}
               okText={messages('pay.key60'/*确认失败*/)}
               width={500}>
          <div style={{marginTop:'20px'}}>
            <Alert
              message={<div><span style={{marginRight:10,fontSize:14}}>{messages('pay.key65'/*将付款状态更改为*/)}</span><Badge status="error" text={messages('pay.key69'/*支付失败*/)}/></div>}
              description={<div style={{fontSize:12,color:'red'}}>{messages('pay.key70'/*请务必向银行确认该付款支付失败，以免产生重复支付*/)}</div>}
              type="warning"
              showIcon
            />
          </div>
        </Modal>
      </Spin>
    )
  }

}

PayPaying.contextTypes = {
  router: React.PropTypes.object
};

PayPaying.propTypes = {
  subTab: React.PropTypes.string,
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    tenantMode: state.main.tenantMode
  }
}

const wrappedPayPaying = Form.create()(PayPaying);
const WrappedPayPayingHoc = CheckModal(wrappedPayPaying);
export default connect(mapStateToProps)(WrappedPayPayingHoc);
